/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.nio.*;
import java.net.*;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ClientController implements Runnable{
    private final SelectionKey key;
    
    private final Selector selector;
    
    ClientController(SelectionKey key, Selector selector) {
        this.key = key;
        this.selector = selector;
    }
    
    public void run() {
        try {
            if (key.isWritable()) {
                System.out.println("Key ready to perform read() : " + key.channel().toString());

                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer bb = null;

                Long num = new Long(Server.next());
                bb = ByteBuffer.wrap(num.toString().getBytes());
                client.write(bb);
                bb.clear();
      
                client.register(selector, SelectionKey.OP_READ);
            }
            else if(key.isReadable()) {
                ByteBuffer bb = ByteBuffer.allocate(1024);
         
                SocketChannel client = (SocketChannel) key.channel();
                client.read(bb);

                bb.flip();
                byte[] array = new byte[bb.limit()];
                bb.get(array);
         
                client.register(selector, SelectionKey.OP_WRITE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
